import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dotted_line/dotted_line.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rtk/api/api.dart';
import 'package:flutter_rtk/common/assets.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_rtk/entities/current_project_entity.dart';
import 'package:flutter_rtk/entities/tools_entity.dart';
import 'package:flutter_rtk/models/app_model.dart';
import 'package:flutter_rtk/models/user_info_model.dart';
import 'package:flutter_rtk/router/index.dart';
import 'package:flutter_rtk/service/connectivity_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class ToolsPage extends StatefulWidget {
  const ToolsPage({super.key});

  @override
  State<ToolsPage> createState() => _ToolsPageState();
}

class _ToolsPageState extends State<ToolsPage> with AutomaticKeepAliveClientMixin {
  CurrentProjectEntity? _currentProjectInfo;

  // 全部工具
  List<ToolsEntity> menus = [];

  //
  List<ToolsEntity> tempTools = [];

  Widget _buildMainView() {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: mainAppBar(title: "工具"),
      body: CustomScrollView(slivers: [
        SliverToBoxAdapter(child: Container(height: 20.h, color: const Color(0xFFF4F4F4))),
        _buildCommonTools(),
        SliverToBoxAdapter(child: Container(height: 20.h, color: const Color(0xFFF4F4F4))),
        _buildAllTools(),
      ]),
    );
  }

  Widget _buildAllTools() {
    int groupCount = menus.length;
    // 四个分组 + 标题
    double groupTitleHeight = 70.h; //  分组标题
    double separatorHeight = 20.h; // 分组之间间隔高度
    double singleRowHeight = 155.h; // 单行工具高度
    double wholeContentHeight = 0;
    for (ToolsEntity element in menus) {
      int count = element.children.length;
      int rows = (count + 3) ~/ 4; // 单分组所需行数
      wholeContentHeight += rows * singleRowHeight;
    }
    double wholeHeight = groupCount * (groupTitleHeight + separatorHeight) + wholeContentHeight;
    return SliverToBoxAdapter(
      child: SizedBox(
        width: double.infinity,
        height: wholeHeight,
        child: ListView.separated(
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (context, idx) {
            int count = menus[idx].children.length; // 当前分组下所有工具数
            int rows = (count + 3) ~/ 4; // 当前分组所需行数
            double contentHeight = rows * singleRowHeight; // 当前分组总高度 = 分组标题高度 + 内容高度(行数*单行高度)
            return _buildSingleGroup(contentHeight: contentHeight, groupTitleHeight: groupTitleHeight, groupIdx: idx, singleRowHeight: singleRowHeight);
          },
          separatorBuilder: (context, idx) => Container(height: separatorHeight, color: const Color(0xFFF4F4F4)),
          itemCount: groupCount,
        ),
      ),
    );
  }

  Widget _buildSingleGroup({required double contentHeight, required double groupTitleHeight, required int groupIdx, double? singleRowHeight}) {
    ToolsEntity groupMenu = menus[groupIdx];
    List<ToolsEntity> childMenus = groupMenu.children.map((e) => ToolsEntity.fromJson(e)).toList();
    int rows = (childMenus.length + 3) ~/ 4;
    double singleGroupHeight = contentHeight + groupTitleHeight;
    return Container(
      width: double.infinity,
      height: singleGroupHeight,
      color: Colors.white,
      child: Column(children: [
        // 分组标题
        Container(
          width: double.infinity,
          height: groupTitleHeight,
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(left: 33.w),
          child: Text(groupMenu.name, style: TextStyle(fontSize: 30.sp, fontWeight: FontWeight.w600, color: const Color(0xFF121212))),
        ),
        // 分组下菜单信息
        SizedBox(
          width: double.infinity,
          height: contentHeight,
          child: ListView.builder(
            itemBuilder: (context, rowIdx) {
              int endIdx = rowIdx * 4 + 4 < childMenus.length ? rowIdx * 4 + 4 : childMenus.length;
              return _buildSingleRowTool(width: double.infinity, height: singleRowHeight ?? 155.h, menuIdx: rowIdx, menus: childMenus.sublist(rowIdx * 4, endIdx));
            },
            itemCount: rows,
            physics: const NeverScrollableScrollPhysics(),
          ),
        ),
      ]),
    );
  }

  Widget _buildCommonTools() {
    return SliverToBoxAdapter(
      child: Consumer<AppModel>(builder: (context, appModel, child) {
        int rows = appModel.collectionTools.length > 4 ? 2 : 1;
        if (appModel.collectionTools.isEmpty) {
          rows = 0;
        }
        return Container(
          width: double.infinity,
          height: (160 + (162 * rows)).h,
          color: Colors.white,
          child: Column(children: [
            _buildCommonToolsHeader(),
            // tools
            SizedBox(
              width: double.infinity,
              height: (162 * rows).h,
              child: ListView.builder(
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (context, rowIdx) {
                  int endIdx = rowIdx * 4 + 4 < appModel.collectionTools.length ? rowIdx * 4 + 4 : appModel.collectionTools.length;
                  return _buildSingleRowTool(width: double.infinity, height: 162.h, menuIdx: rowIdx, isCommonTool: true, menus: appModel.collectionTools.sublist(rowIdx * 4, endIdx));
                },
                itemCount: rows,
              ),
            ),
            SizedBox(height: 17.h),
            // line
            Consumer<AppModel>(builder: (context, appModel, child) {
              return Container(
                width: double.infinity,
                height: 2.h,
                margin: EdgeInsets.only(left: 41.w, right: 34.w),
                child: DottedLine(dashColor: const Color(0xFF979797), lineThickness: 1.h),
              );
            }),
            SizedBox(height: 14.h),
            // 以上工具展示在首页
            _buildCommonToolsBottom(),
            // SizedBox(height: 19.h),
          ]),
        );
      }),
    );
  }

  _buildCommonToolsBottom() {
    return SizedBox(
      width: double.infinity,
      height: 31.h,
      child: Center(
        child: SizedBox(
          width: (65 * 2 + 27 * 2 + 225).w,
          child: Row(children: [
            Container(
              width: 65.w,
              height: 3.h,
              decoration: const BoxDecoration(
                gradient: LinearGradient(colors: [Color(0xFFEEEEEE), Color(0xFFD8D8D8)]),
              ),
            ),
            Container(
              width: 7.w,
              height: 7.h,
              margin: EdgeInsets.only(left: 6.w, right: 14.w),
              decoration: BoxDecoration(
                color: const Color(0xFFD8D8D8),
                borderRadius: BorderRadius.all(Radius.circular(7.r)),
              ),
            ),
            Flexible(
              child: SizedBox(
                height: 31.h,
                child: Text("以上工具展示在首页", style: TextStyle(fontSize: 24.sp, color: const Color(0xFF999999))),
              ),
            ),
            Container(
              width: 7.w,
              height: 7.h,
              margin: EdgeInsets.only(left: 14.w, right: 6.w),
              decoration: BoxDecoration(
                color: const Color(0xFFD8D8D8),
                borderRadius: BorderRadius.all(Radius.circular(7.r)),
              ),
            ),
            Container(
              width: 65.w,
              height: 3.h,
              decoration: const BoxDecoration(
                gradient: LinearGradient(colors: [Color(0xFFD8D8D8), Color(0xFFEEEEEE)]),
              ),
            ),
          ]),
        ),
      ),
    );
  }

  _buildCommonToolsHeader() {
    return Container(
      width: double.infinity,
      height: 77.h,
      padding: EdgeInsets.symmetric(horizontal: 25.w),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [
        Container(width: 140.w, height: 77.h, alignment: Alignment.center, child: Text("常用工具", style: TextStyle(fontSize: 32.sp, color: Colors.black, fontWeight: FontWeight.normal))),
        const Spacer(),
        _buildToolsEditButton(),
      ]),
    );
  }

  Widget _buildSingleRowTool({required double width, required double height, required int menuIdx, required List<ToolsEntity> menus, bool isCommonTool = false}) {
    int length = menus.length;
    ToolsEntity? m1 = length > 0 ? menus[0] : null;
    ToolsEntity? m2 = length > 1 ? menus[1] : null;
    ToolsEntity? m3 = length > 2 ? menus[2] : null;
    ToolsEntity? m4 = length > 3 ? menus[3] : null;
    return SizedBox(
      width: width,
      height: height,
      child: Consumer<AppModel>(builder: (context, appModel, child) {
        return Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
          m1 != null ? Flexible(child: _buildToolItem(menu: m1, isCommonTool: isCommonTool)) : SizedBox(width: 162.w),
          m2 != null ? Flexible(child: _buildToolItem(menu: m2, isCommonTool: isCommonTool)) : SizedBox(width: 162.w),
          m3 != null ? Flexible(child: _buildToolItem(menu: m3, isCommonTool: isCommonTool)) : SizedBox(width: 162.w),
          m4 != null ? Flexible(child: _buildToolItem(menu: m4, isCommonTool: isCommonTool)) : SizedBox(width: 162.w),
        ]);
      }),
    );
  }

  _buildToolsEditButton() {
    if (!ConnectivityService.to.isOnline) {
      // 如果没网，不允许编辑菜单
      return SizedBox(width: 260.w, height: 44.w);
    }
    return Consumer2<AppModel, UserInfoModel>(builder: (context, appModel, userInfoModel, child) {
      if (appModel.appPageIsEdit) {
        return Container(
          width: 260.w,
          height: 44.w,
          alignment: Alignment.center,
          child: Row(children: [
            // cancel
            SizedBox(
              width: 120.w,
              height: 44.w,
              child: ElevatedButton(
                style: ButtonStyle(
                  splashFactory: NoSplash.splashFactory,
                  backgroundColor: MaterialStateProperty.all(Colors.white),
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(44.r),
                      side: const BorderSide(width: 1, color: AppConstants.brandColor),
                    ),
                  ),
                  padding: MaterialStateProperty.all(EdgeInsets.zero),
                  elevation: MaterialStateProperty.all(0),
                ),
                onPressed: () {
                  // cancel tools edit status
                  appModel.collectionTools.removeWhere((element) => tempTools.contains(element));
                  context.read<AppModel>().changeEditState();
                  tempTools.clear();
                  setState(() {});
                },
                child: Text("取消", style: TextStyle(color: AppConstants.brandColor, fontSize: 24.sp)),
              ),
            ),
            SizedBox(width: 20.w),
            // confirm
            SizedBox(
              width: 120.w,
              height: 44.w,
              child: ElevatedButton(
                style: ButtonStyle(
                  splashFactory: NoSplash.splashFactory,
                  backgroundColor: MaterialStateProperty.all(AppConstants.brandColor),
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(44.r),
                      side: const BorderSide(width: 1, color: AppConstants.brandColor),
                    ),
                  ),
                  padding: MaterialStateProperty.all(EdgeInsets.zero),
                  elevation: MaterialStateProperty.all(0),
                ),
                onPressed: () async {
                  // if (tempTools.isEmpty) {
                  //   context.read<AppModel>().changeEditState();
                  //   return;
                  // }
                  CurrentProjectEntity project = context.read<AppModel>().currentProjectInfo!;
                  List tools = [];
                  if (tempTools.isNotEmpty) {
                    tools = tempTools.map((ToolsEntity e) => {"path": e.path, "menuNameZh": e.name, "filePath": e.filePath, "projectCode": project.projectCode, "projectId": project.projectId}).toList();
                  }
                  try {
                    await AppApi.addCollectionTools(tools: tools);
                    showToast("设置常用工具成功");
                    tempTools.clear();
                    setState(() {});
                    // cancel tools edit status
                    context.read<AppModel>().changeEditState();
                  } catch (e, stack) {
                    debugPrintStack(stackTrace: stack);
                    showToast("收藏失败, $e");
                  }
                },
                child: Text("完成", style: TextStyle(color: Colors.white, fontSize: 24.sp)),
              ),
            ),
          ]),
        );
      }
      return Container(
        width: 120.w,
        height: 44.w,
        alignment: Alignment.center,
        child: ElevatedButton.icon(
          style: ButtonStyle(
            splashFactory: NoSplash.splashFactory,
            backgroundColor: MaterialStateProperty.all(const Color(0xFFFFF4F1)),
            shape: MaterialStateProperty.all(
              RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(44.r),
                side: const BorderSide(width: 1, color: Color(0xFFFF8200)),
              ),
            ),
            padding: MaterialStateProperty.all(EdgeInsets.zero),
            elevation: MaterialStateProperty.all(0),
          ),
          onPressed: () {
            if (appModel.collectionTools.isNotEmpty) {
              tempTools.addAll(appModel.collectionTools);
            }
            context.read<AppModel>().changeEditState();
          },
          label: Text("编辑", style: TextStyle(color: const Color(0xFFFF8200), fontSize: 24.sp)),
          icon: SizedBox(width: 22.w, height: 22.w, child: Image.asset(AppAssets.toolsEdit)),
        ),
      );
    });
  }

  Widget _buildToolItem({required ToolsEntity menu, bool isCommonTool = false}) {
    return Consumer<AppModel>(builder: (context, appModel, child) {
      return InkWell(
        onTap: () {
          if (appModel.appPageIsEdit) {
            if (isCommonTool) {
              // 移除收藏
              appModel.collectionTools.removeWhere((e) => e.id == menu.id);
              tempTools.remove(menu);
              setState(() {});
            } else {
              // 添加进收藏
              if (appModel.collectionTools.length >= 7) {
                showToast("常用工具最多添加7个");
                return;
              }
              if (!appModel.collectionTools.any((element) => element.id == menu.id)) {
                appModel.collectionTools.add(menu);
                tempTools.add(menu);
                setState(() {});
              }
            }
          } else {
            try {
              jsonDecode(menu.path);
            } catch (e) {
              //
              if (menu.path.startsWith("/")) {
                Navigator.pushNamed(context, AppRouters.webview, arguments: {"title": menu.name, "url": menu.path});
                return;
              }
            }
            Map path = jsonDecode(menu.path);
            if (path['Type'] == "H5") {
              Navigator.pushNamed(context, AppRouters.webview, arguments: {"title": menu.name, "url": path['Url']});
            } else {
              showToast("功能待开放,请联系工作人员");
            }
          }
        },
        child: _buildSingleToolItemBtn(menu, appModel, isCommonTool),
      );
    });
  }

  _buildSingleToolItemBtn(ToolsEntity menu, AppModel appModel, bool isCommonTool) {
    return Stack(children: [
      Container(
        width: 162.w,
        height: 162.h,
        alignment: Alignment.center,
        child: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [
          SizedBox(width: 84.w, height: 84.h, child: ConnectivityService.to.isOnline ? CachedNetworkImage(imageUrl: menu.filePath) : Image.asset(AppAssets.offlineIcon)),
          SizedBox(height: 10.h),
          FittedBox(child: Text(menu.name, style: TextStyle(fontSize: 24.sp, color: const Color(0xFF333333), fontWeight: FontWeight.normal))),
        ]),
      ),
      appModel.appPageIsEdit
          ? isCommonTool
              ? Positioned(top: 12.h, right: 16.w, child: SizedBox(width: 30.w, height: 30.h, child: Image.asset(AppAssets.toolsCanRemove)))
              : Positioned(
                  top: 12.h,
                  right: 16.w,
                  child: SizedBox(
                    width: 30.w,
                    height: 30.h,
                    child: appModel.collectionTools.any((ToolsEntity e) => e.name == menu.name) ? Image.asset(AppAssets.toolsSelected) : Image.asset(AppAssets.toolsUnselect),
                  ),
                )
          : const SizedBox.shrink()
    ]);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _buildMainView();
  }

  @override
  void initState() {
    super.initState();
    _currentProjectInfo = context.read<AppModel>().currentProjectInfo;
    if (_currentProjectInfo != null) {
      if (ConnectivityService.to.isOnline) {
        _fetchAllTools(_currentProjectInfo!, (tools) => context.read<AppModel>().setAllTools(tools));
      }
    }
  }

  _fetchAllTools(CurrentProjectEntity currentProjectInfo, Function(dynamic tools) callback) async {
    try {
      List<ToolsEntity> tools = await AppApi.getAllTools(projectId: currentProjectInfo.projectId, projectCode: currentProjectInfo.projectCode, deptCode: currentProjectInfo.deptCode);
      callback(tools);
      setState(() {
        menus = tools;
      });
    } catch (e, stack) {
      debugPrintStack(stackTrace: stack, label: "获取工具信息失败:$e");
      showToast("获取工具信息失败:$e");
    }
  }

  @override
  bool get wantKeepAlive => true;
}
